using System;
using MyReactivity;
using MyReactivity.Abstractions;
using Project.Models;
using Project.ViewModels.Abstractions;

namespace Project.ViewModels
{
    public class WorldInventoryViewModel : ViewModelBase<WorldInventory>, IDisposable
    {
        private readonly ItemConfigsStorage _itemConfigsStorage;
        private readonly ReactiveList<SlotViewModel> _slotViewModels;

        public WorldInventoryViewModel(WorldInventory model, ItemConfigsStorage itemConfigsStorage) : base(model)
        {
            _itemConfigsStorage = itemConfigsStorage;
            _slotViewModels = new ReactiveList<SlotViewModel>();

            for (int i = 0, length = Model.Slots.Count; i < length; i++)
                OnSlotsElementAdded(i, Model.Slots[i]);

            Model.Slots.ElementAdded += OnSlotsElementAdded;
        }

        public IReadOnlyReactiveList<SlotViewModel> SlotViewModels => _slotViewModels;

        public void Dispose()
        {
            Model.Slots.ElementAdded -= OnSlotsElementAdded;
        }

        private void OnSlotsElementAdded(int index, Slot addedSlot) =>
            _slotViewModels.Insert(index, new SlotViewModel(addedSlot, _itemConfigsStorage));
    }
}
